package com.wx.service;


import com.wx.entity.WxProperties;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class WxService {

    private Logger logger = LoggerFactory.getLogger(WxService.class);

    private WxProperties wxProperties;
    private static String WX_UNIONID_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";

    public WxService(WxProperties wxProperties){
        this.wxProperties = wxProperties;
    }

    private String getTokenUrl(){
        return  String.format("https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=STATE",wxProperties.getAppId(),getRedirectUri());
    }



    /**
     * 	获取跳转的URL，需要进行URLEncoding
     * @return
     */
    private  String getRedirectUri(){
        try {
            String url = URLEncoder.encode(wxProperties.getRedirectUrl(),"UTF-8");
            return url;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 	获取WxLoginUrl
     * @return
     */
    public  String getWxLoginUrl(){
        return getTokenUrl();
    }

    /*
     * {
     *   "access_token":"29_g8Xlr5XkGKcM4QrBreiL0M5ZwJIzK0nH9c2hpeRxbLzY6nT1kTyC9vSWsvDtajRsstwsdYHsZZUj2l4dUdSdWV3msRPHGR4N4qKgtUmfWN0",
     *   "expires_in":7200,
     *   "refresh_token":"29_k_RqC_GScNagTZ8lSjTF70RtrIqyrzYaac7d4Dcj_cj6bqYJmuveB-TMjBYs0Lk-20KR0xfJZp8zTZPiKAwSr9CerfTTPq1vzO6kHN_hVxM",
     *   "openid":"oA4lF0_aopzL6P9ym9J9Fp7SehfY",
     *   "scope":"snsapi_login",
     *   "unionid":"o7eAFw8YwtvxI3KnTqKZCeXqQBZw"
     * }
     */
    public  JSONObject getAccessToken(String code){
        String WX_ACCESSTOKEN_URL = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=scode&grant_type=authorization_code",wxProperties.getAppId(),wxProperties.getSecret());
        WX_ACCESSTOKEN_URL = WX_ACCESSTOKEN_URL.replace("scode",code);
        JSONObject jsonRes = execute(WX_ACCESSTOKEN_URL,"GET");

        //返回结果包含 errcode 或者 errmsg的时候说明获取TOKEN失败
        if(!jsonRes.isNull("errcode") || !jsonRes.isNull("errmsg")){
            logger.error("errcode: "+jsonRes.getInt("errcode"));
            logger.error("errmsg: "+jsonRes.getString("errmsg"));
            return jsonRes;
        }

        String accessToken = jsonRes.getString("access_token");
        String openId = jsonRes.getString("openid");

        logger.info("===============================================");
        logger.info("access_token: "+accessToken);
        logger.info("expires_in: "+jsonRes.getInt("expires_in"));
        logger.info("refresh_token: "+jsonRes.getString("refresh_token"));
        logger.info("openid: "+openId);
        logger.info("scope: "+jsonRes.getString("scope"));
        logger.info("unionid: "+jsonRes.getString("unionid"));
        logger.info("===============================================");


        /*
         * {
         *   "country":"CN",
         *   "unionid":"o7eAFw8YwtvxI3KnTqKZCeXqQBZw",
         *   "province":"Gansu",
         *   "city":"Qingyang",
         *   "openid":"oA4lF0_aopzL6P9ym9J9Fp7SehfY",
         *   "sex":1,
         *   "nickname":"我们好像在哪儿见过",
         *   "headimgurl":"http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIwDsE0A0FKAuvtXV9Noia9lCY1I19icKHmdp8wvtXOKxC0xkvc2EpQNsJvnOibRrQIjhxN4uX1spylg/132",
         *   "language":"zh_CN",
         *   "privilege":[]
         * }
         */

        JSONObject info = execute(String.format(WX_UNIONID_URL,accessToken,openId),"GET");
        jsonRes.put("unionid", info.getString("unionid"));
        jsonRes.put("nickname", info.getString("nickname"));
        jsonRes.put("headimgurl", info.getString("headimgurl"));
        jsonRes.put("privilege", info.getJSONArray("privilege"));

        return jsonRes;
    }

    /**
     * 	封装一个发送HTTP请求的方法
     * @param url
     * @param method
     * @return
     */
    private static JSONObject execute(String url, String method){
        String res = sendRequest(url,method);
        return new JSONObject(res);
    }


    /**
     * 	发送HTTP请求
     * @param urlParam
     * @param requestType
     * @return
     */
    public static String sendRequest(String urlParam,String requestType) {

        HttpURLConnection con = null;
        BufferedReader buffer = null;
        StringBuffer resultBuffer = null;

        try {
            URL url = new URL(urlParam);
            //得到连接对象
            con = (HttpURLConnection) url.openConnection();
            //设置请求类型
            con.setRequestMethod(requestType);
            //设置请求需要返回的数据类型和字符集类型
            con.setRequestProperty("Content-Type", "application/json;charset=GBK");
            //允许写出
            con.setDoOutput(true);
            //允许读入
            con.setDoInput(true);
            //不使用缓存
            con.setUseCaches(false);
            //得到响应码
            int responseCode = con.getResponseCode();

            if(responseCode == HttpURLConnection.HTTP_OK){
                //得到响应流
                InputStream inputStream = con.getInputStream();
                //将响应流转换成字符串
                resultBuffer = new StringBuffer();
                String line;
                buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                while ((line = buffer.readLine()) != null) {
                    resultBuffer.append(line);
                }
                return resultBuffer.toString();
            }

        }catch(Exception e) {
            e.printStackTrace();
        }
        return "";
    }


}
